/**
 * @fileOverview 宝塔API。
 * @author [mac-xiang]
 */
import axios from "axios";
import { md5 } from "js-md5";
import FormData from "form-data";

type obj = Record<string, any>;

axios.defaults.withCredentials = true;
const url = `http://${process.env.svrIP}:${process.env.btPort || 80}`;
function obj2Form(p: obj) {
  const ret = new FormData();
  for (const k in p) {
    if (p.hasOwnProperty(k)) {
      ret.append(k, p[k]);
    }
  }
  return ret;
}
function post(api: string, p?: obj) {
  const
    api_sk = process.env.btSK || "",
    request_time = parseInt(new Date().getTime() / 1000 + ""),
    formData = obj2Form(Object.assign({
      api_sk,
      request_time,
      request_token: md5(request_time + md5(api_sk)),
    }, p || {}));
  return axios.post(url + api, formData, {
    headers: { "Content-Type": `multipart/form-data; boundary=${formData.getBoundary()}` }
  });
  // return axios.get()
}
export function restartServer(project_name: string) {
  return post("/project/java/restart_project", { project_name });
}
export function stopServer(project_name: string) {
  return post("/project/java/stop_project", { project_name });
}
export function startServer(project_name: string) {
  return post("/project/java/start_project", { project_name });
}